package com.example.app1

import android.animation.ObjectAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import androidx.core.graphics.toColorInt
import kotlin.math.abs
import kotlin.math.asin
import kotlin.math.cos
import kotlin.math.pow
import kotlin.math.sin
import kotlin.math.sqrt

class PieChartView(context: Context?, attrs: AttributeSet?) : View(context, attrs) {

    private val radius = 150.dp
    private val dis = 20.dp
    private val colors = arrayOf(
        Color.RED,
        Color.BLUE,
        Color.YELLOW,
        "#FF9C27B0".toColorInt(),
        "#FFFF5722".toColorInt()
    )
    private val percent = arrayOf(0.2f, 0.2f, 0.3f, 0.1f, 0.2f)
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private var highLight = -1
    private var offsetFraction = 0f
        set(value) {
            field = value
            invalidate()
        }
    private val offsetAnimation = ObjectAnimator.ofFloat(this, "offsetFraction", 0f, 1f)

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        var startAngle = 0f
        colors.forEachIndexed { index, color ->
            paint.color = color
            val sweep = percent[index] * 360
            if (index == highLight) {
                val angle = (sweep / 2) + startAngle.toDouble()
                val dx = cos(Math.toRadians(angle)) * dis * offsetFraction
                val dy = sin(Math.toRadians(angle)) * dis * offsetFraction
                // translation也行
                canvas.drawArc(
                    width / 2f - radius + dx.toFloat(),
                    height / 2f - radius + dy.toFloat(),
                    width / 2f + radius + dx.toFloat(),
                    height / 2f + radius + dy.toFloat(),
                    startAngle,
                    sweep,
                    true,
                    paint
                )
            } else {
                canvas.drawArc(
                    width / 2f - radius,
                    height / 2f - radius,
                    width / 2f + radius,
                    height / 2f + radius,
                    startAngle,
                    sweep,
                    true,
                    paint
                )
            }
            startAngle += sweep
        }
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        if (event.actionMasked == MotionEvent.ACTION_DOWN) {
            highLightIfNeed(event)
        }
        return false
    }

    private fun highLightIfNeed(event: MotionEvent) {
        // 根据点击的位置，得出点击在哪个扇形上，然后高亮显示
        val x = event.x
        val y = event.y
        // 计算到圆心的距离
        val distance = sqrt(abs(x - width / 2.0).pow(2.0) + abs(y - height / 2.0).pow(2.0))
        if (distance <= radius) {
            println("点在圆上了")
            // arcsin x = a sin a = x
            // arcsin(sin a) = a
            // 只有+-90°，需要自己确定象限
            val degree = Math.toDegrees(asin((y - height / 2f) / distance))
            println(degree)
            val finalDegree = getFinalDegree(degree, x)
            var sum = 0f
            for ((index, i) in percent.withIndex()) {
                sum += i
                println("$sum, ${sum * 360}")
                if (sum * 360 >= finalDegree) {
                    highLight = index
                    offsetAnimation.start()
                    break
                }
            }
            println(highLight)
        }
    }

    private fun getFinalDegree(degree: Double, x: Float): Double {
        // y轴向下哦
        var finalDegree = 0.0
        if (degree > 0) {
            finalDegree = if (x > width / 2f) {
                // 第一象限
                degree
            } else if (x < width / 2f) {
                // 第二象限
                180 - degree
            } else {
                degree
            }
        } else if (degree < 0) {
            finalDegree = if (x > width / 2f) {
                // 第四象限
                360 + degree
            } else if (x < width / 2f) {
                // 第三象限
                180 - degree
            } else {
                180 - degree
            }
        }
        println(finalDegree)
        return finalDegree
    }
}